package com.example.starter.qrbar.barcode;

import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @author 王令
 * @since 2023/11/24 10:23
 */
@Slf4j
public class BarcodeGenerator implements Generator {

    private final static ThreadBarcode BARCODE = new ThreadBarcode();

    @Override
    public Generator width(int width) {
        if (BARCODE.initialized()) {
            log.warn("width应在generate方法之前设置，此次设置不生效");
        } else  {
            BARCODE.setWidth(width);
        }
        return this;
    }

    @Override
    public Generator height(int height) {
        if (BARCODE.initialized()) {
            log.warn("height应在generate方法之前设置，此次设置不生效");
        } else {
            BARCODE.setHeight(height);
        }
        return this;
    }

    @Override
    public Generator generate(String text) throws WriterException {
        BARCODE.setMatrix(new MultiFormatWriter(), text);
        return this;
    }

    @Override
    public void toStream(OutputStream output) throws IOException {
        try {
            MatrixToImageWriter.writeToStream(BARCODE.getMatrix(), "PNG", output);
        } finally {
            clear();
        }
    }

    @Override
    public void clear() {
        BARCODE.remove();
    }
}
